<template>
    <basic-container>
        <avue-crud :option="options" v-model:search="search" v-model:page="page" v-model="form" :table-loading="loading"
            :data="data" :permission="permissionList" :before-open="beforeOpen" ref="crud" @row-update="rowUpdate"
            @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
            @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" @on-load="onLoad">
            <template #menu-left>
                <el-button type="danger" icon="el-icon-delete" plain v-if="permission.specimen_delete"
                    @click="handleDelete">删 除
                </el-button>
                <!-- <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导 出
        </el-button> -->
            </template>
        </avue-crud>
    </basic-container>
</template>

<script setup>
import { getList, getDetail, add, update, remove } from '@/api/specimen/specimen';
import option from '@/option/specimen/specimen';
import { useStore } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import website from '@/config/website';
import { findObject } from '@smallwei/avue';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { change } from '@/api/job/jobinfo';
const router = useRouter();
const crud = ref(null);
const store = useStore();
const form = ref({});
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
    pageSize: 10,
    currentPage: 1,
    total: 0,
});
const selectionList = ref([]);
const options = ref(option);
const data = ref([]);

const props = defineProps({
    routerQuery: {
        type: Object,
        default: () => { }
    },
});

// permissionList 计算属性
const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
    addBtn: validData(permission.value.specimen_add, false),
    viewBtn: validData(permission.value.specimen_view, false),
    delBtn: validData(permission.value.specimen_delete, false),
    editBtn: validData(permission.value.specimen_edit, false),
}));

// ids 计算属性
const ids = computed(() => {
    return selectionList.value.map(ele => ele.id).join(',');
});

const rowSave = (row, done, loading) => {
    props.routerQuery ? row.trial = props.routerQuery.trialId : ''
    add(row)
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
            done();
        })
        .catch(error => {
            loading();
            window.console.console.log(error);
        });
};

const rowUpdate = (row, index, done, loading) => {
    update(row)
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
            done();
        })
        .catch(error => {
            loading();
            window.console.console.log(error);
        });
};

const rowDel = row => {
    ElMessageBox.confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return remove(row.id);
        })
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
        });
};

const handleDelete = () => {
    if (selectionList.value.length === 0) {
        ElMessage.warning('请选择至少一条数据');
        return;
    }
    ElMessageBox.confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return remove(ids.value);
        })
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
        });
};

const handleExport = () => {
    const downloadUrl = `/blade-specimen/specimen/export-specimen?${website.tokenHeader}=${getToken()}`;
    const { name } = query.value;
    let values = {
        name_: name,
    };

    ElMessageBox.confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
            downloadXls(res.data, `疾病管理${dateNow()}.xlsx`);
            NProgress.done();
        });
    });
};

const beforeOpen = (done, type) => {
    if (['add'].includes(type)) {
        const createUser = findObject(options.value.column, 'createUser');
        createUser.value = userInfo.value.user_id;
    }
    if (['edit', 'view'].includes(type)) {
        getDetail(form.value.id).then(res => {
            form.value = res.data.data;
        });
    }
    done();
};

const searchReset = () => {
    query.value = {};
    onLoad(page.value);
};

const searchChange = (params, done) => {
    query.value = params;
    page.value.currentPage = 1;
    onLoad(page.value, params);
    done();
};

const selectionChange = list => {
    selectionList.value = list;
};

const selectionClear = () => {
    selectionList.value = [];
    crud.value.toggleSelection();
};

const currentChange = currentPage => {
    page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
    page.value.pageSize = pageSize;
};

const refreshChange = () => {
    onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
    loading.value = true;
    let values = {
        descs: 'create_time',
        ...params,
    };
    props.routerQuery ? values.trial = props.routerQuery.trialId : ''
    getList(page.currentPage, page.pageSize, values).then(res => {
        const DATA = res.data.data;
        page.total = DATA.total;
        data.value = DATA.records;
        loading.value = false;
        selectionClear();
    });
};
</script>

<style></style>
